<template>
  <div class="data-mapping-container" v-loading="loading">
    <div class="panel-header1">
          <h3 class="panel-title">
          一对多映射
            <span v-if="codeId" class="code-id">ID: {{ codeId }}</span>
          </h3>
          
          <div class="panel-actions">
            <el-button type="success" size="small" icon="el-icon-view" @click="handlePreview">预览数据</el-button>

            <el-button 
            type="primary" 
             size="small" 
            icon="el-icon-document-checked" 
            @click="hadnleSaveCondtion" 
            >保存规则</el-button>
          </div>
    </div>      
    <div class="mapping-content">
      <!-- 左侧字段选择区 -->
      <div class="field-selection-panel">
        <div class="panel-header">
          <h3>入库字段</h3>
          <el-tooltip content="全选/取消所有入库字段" placement="top">
            <el-checkbox 
              v-model="checkedIn" 
              @change="handleChangeCheckAll" 
              v-if="wareList.length > 0"
            >全选</el-checkbox>
          </el-tooltip>
        </div>
        
        <div class="panel-body" v-if="codeId">
          <div class="field-list">
            <el-checkbox-group v-model="checkList" @change="handleGetCheckedWare">
              <div v-for="(item,index) in wareList" :key="index" class="field-item">
                <el-checkbox 
                  :label="item.columnName" 
                  :disabled="item.columnName == 'INSTR_ID' || item.columnName == 'CODE_ID' || item.columnName == 'TULI'|| item.columnName == 'REMARK'"
                >
                  <span class="field-name">{{ item.columnName }}</span>
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </div>
        </div>
        <div v-else class="empty-state">
          <i class="el-icon-s-prompt empty-icon"></i>
          <p>请在左侧选择测点</p>
        </div>
      </div>

      <!-- 右侧配置区 -->
      <div class="configuration-panel">
        <!-- 数据源配置卡片 -->
        <el-card class="config-card data-source-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="card-title"><i class="el-icon-connection"></i> 数据源配置</span>
            <div class="cursor-config">
               <el-button 
                type="primary" 
                icon="el-icon-edit" 
                @click="hadnleAddCondtionMore" 
                size="mini"
              >数据源</el-button>
            </div>
          </div>
          
          <div v-for="(item, index) in conditionList" :key="index" class="source-item">
              <div class="source-card">
                <!-- 数据源基本配置 -->
                    <el-form :model="item" size="small" label-width="100px" class="data-source-form" inline>
                          <el-form-item :label="`数据源${ index + 1 }`">
                            <el-select 
                              v-model="item.dbId" 
                              placeholder="请选择数据源" 
                               @change="handleChangeDbID($event,index,1)" style="width:170px"
                            >
                              <el-option 
                                v-for="(item,index) in wareSelectList" 
                                :key="index" 
                                :label="item.alias" 
                                :value="item.id"
                              ></el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="模式">
                            <el-select 
                              v-model="item.dbSchemaName" 
                              placeholder="请选择模式" 
                              @change="handleChangeDbSchemaId($event,index,1)"
                              @focus="handleFocusDbSchemaId(item.dbId,1)" 
                              :disabled="!item.dbId"
                              style="width:170px"
                              value-key="schemaId"
                            >
                              <el-option 
                                v-for="(item,index) in dbSchemas" 
                                :key="index" 
                                :label="item.schemaName" 
                                :value="item"
                              ></el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="数据表">
                            <el-select 
                              v-model="item.dictTableName" 
                              placeholder="请选择数据表" 
                             @change="handleChangeDictTableID($event,index,1)"
                             @focus="handleFocusDictTableID(item.dictVersionId)"
                              :disabled="!item.dbSchemaId"
                              style="width:170px"
                              value-key="id"
                            >
                              <el-option 
                                v-for="(item,index) in dictSelect" 
                                :key="index" 
                                :label="item.tableName" 
                                :value="item"
                              ></el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="时间列">
                            <el-select 
                              v-model="item.dictTimeColumnName" 
                              placeholder="请选择时间列" 
                              :disabled="!item.dictTableId"
                              style="width:170px"
                              @change="handleChangedictTimeColumnId($event,index,1)" 
                              @focus="handleFocusdictTimeColumnId(item.dictTableId)"
                              value-key="id"
                            >
                              <el-option 
                                v-for="(item,index) in versionColumnSelect" 
                                :key="index" 
                                :label="item.columnName" 
                                :value="item"
                              ></el-option>
                            </el-select>
                          </el-form-item>
                          <el-form-item label="主表">
                            <el-checkbox 
                                  v-model="item.isMaster" 
                                  @change="handleChangeMainSelect($event, index)"
                                  class="master-checkbox"
                                ></el-checkbox>
                          </el-form-item>
                          <el-form-item label="范围区间" style="margin-left:160px;" v-if="!item.isMaster">
                            <el-input 
                              v-model="item.matchSeconds" 
                              placeholder="范围区间" 
                              class="seconds-input"
                              size="small"
                            >
                           <template slot="append">秒</template>
                          </el-input>
                          </el-form-item>
                    </el-form>
                    
                    
                    <!-- <el-button 
                      type="danger" 
                      icon="el-icon-delete" 
                      @click="hadnleDelCondtion(index)" 
                      size="small"
                      class="delete-btn"
                      v-if="conditionList.length > 1"
                    >
                      删除
                    </el-button> -->
                
                <!-- 时间范围和条件配置 -->
                 <el-divider></el-divider>
                <div class="condition-config">
                  <div class="condition-actions">
                    <div class="section-header">过滤条件</div>
                    <el-button 
                      type="primary" 
                      icon="el-icon-plus" 
                      @click="hadnleAddCondtionItem(index)" 
                      size="mini"
                      class="add-condition-btn"
                    >
                      添加条件
                    </el-button>
                  </div>
                  
                  <!-- 条件列表 -->
                  <div v-for="(subItem, subIndex) in item.conditions" :key="subIndex" class="condition-row">
                    <div class="condition-fields">
                      <el-select 
                        v-model="subItem.dictColumnName" 
                        placeholder="选择列" 
                        size="small" 
                        @change="handleChangeColumnName($event, index, subIndex)" 
                        @focus="handleFouceSubItemTimeSelect(item.dictTableId)" 
                        value-key="id"
                        class="condition-select"
                      >
                        <el-option 
                          v-for="(column, colIndex) in versionColumnSelect" 
                          :key="colIndex" 
                          :label="column.columnName" 
                          :value="column"
                        ></el-option>
                      </el-select>
                      
                      <el-select 
                        v-model="subItem.operator" 
                        placeholder="操作符" 
                        size="small" 
                        class="operator-select"
                      >
                        <el-option 
                          v-for="(operator, opIndex) in dbOperator" 
                          :key="opIndex" 
                          :label="operator" 
                          :value="operator"
                        ></el-option>
                      </el-select>
                      
                      <el-input 
                        v-model="subItem.conditionVal" 
                        placeholder="条件值" 
                        size="small"
                        class="value-input"
                      ></el-input>
                    </div>
                    
                    <el-button 
                      type="danger" 
                      icon="el-icon-delete" 
                      @click="handleDelConditionItem(index, subIndex)" 
                      size="mini"
                      style="padding:6px"
                    ></el-button>
                  </div>
                </div>
              </div>
            </div>
        </el-card>

        <!-- 字段映射配置卡片 -->
        <el-card class="config-card field-mapping-card" shadow="hover">
          <div slot="header" class="card-header">
            <span class="card-title"><i class="el-icon-set-up"></i> 字段映射配置</span>
            <div class="cursor-config">
              <span>采集位置：</span>
              <el-input 
                v-model="lastTimeCursor" 
                placeholder="采集位置" 
                size="small"
                style="width: 150px; margin-right: 8px"
              ></el-input>
              <el-button 
                type="primary" 
                icon="el-icon-edit" 
                @click="handleChangeIndex" 
                size="mini"
              >更新</el-button>
            </div>
          </div>
          
          <el-table 
            :data="tableList" border 
            empty-text="请先选择左侧的入库字段"
            height="calc(100vh - 640px)"
          >
            <el-table-column prop="targetColumn" label="入库字段" align="center" width="120"></el-table-column>
            
            <el-table-column label="三方字段" align="center">
              <template slot-scope="scope">
                <el-select 
                  v-model="scope.row.sourceDictColumnId" 
                  placeholder="选择映射字段" 
                  size="small" 
                  clearable 
                  :disabled="scope.row.targetColumn == 'INSTR_ID' || scope.row.targetColumn == 'CODE_ID' || scope.row.targetColumn == 'TULI' || scope.row.targetColumn == 'REMARK'"
                >
                  <el-option
                    v-for="(item,index) in versionColumnSelect"
                    :key="index" :label="item.columnName" :value="item.id"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            
            <el-table-column prop="defaultType" label="策略" align="center" width="120">
              <template slot-scope="scope">
                <el-select 
                  v-model="scope.row.defaultType" 
                  placeholder="选择策略" 
                  size="small" 
                  v-if="!scope.row.sourceDictColumnId"
                >
                  <el-option 
                    v-for="item in dbDefaultType" 
                    :key="item" 
                    :label="item" 
                    :value="item"
                  ></el-option>
                </el-select>
                <span v-else>-</span>
              </template>
            </el-table-column>
            
            <el-table-column prop="defaultVal" label="默认值" align="center" width="150">
              <template slot-scope="scope">
                <el-input 
                  v-model="scope.row.defaultVal" 
                  placeholder="默认值" 
                  size="small" 
                 :disabled="scope.row.targetColumn == 'INSTR_ID' || scope.row.targetColumn == 'CODE_ID' || scope.row.targetColumn == 'TULI' || scope.row.targetColumn == 'REMARK'"
                ></el-input>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog 
      title="数据预览" 
      :visible.sync="previewDialogVisible" 
      width="80%"
      top="5vh"
      custom-class="preview-dialog"
    >
      <div class="preview-content">
        <el-alert
          title="预览数据仅供参考"
          type="info"
          show-icon
          :closable="false"
          style="margin-bottom: 15px"
        ></el-alert>
        
         <el-table :data="dialogTableList" style="width: 100%">
              <el-table-column
              v-for="column in dialogTableTitle"
              :key="column"
              :prop="column"
              :label="column">
              </el-table-column>
          </el-table>
        
        <div class="preview-footer">
          <span class="preview-count">共 {{ dialogTableList.length }} 条记录</span>
          <el-button type="primary" size="small" @click="previewDialogVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import {DBlist,tableColumnList,versionTable,versionColumn,dbConfig,pointSave,pointDetail,pointPreview,PowerPointQueryById,changeIndex} from "@/api/https";
export default {
    props:{
        stationId:{
            type:Number,
            default:0
        },
        codeId:{
            type:Number,
            default:0
        },
        copyCodeID:{
            type:Number,
            default:0
        },
        tabName:{
            type:String,
            default:''
        }
    },
    data() {
        return {
           conditionList:[],
            wareSelectList:[],
            dbSchemas:[],
            activeNames: '1',
            tableList:[],
            wareList:[],
            checkList:[],
            dictSelect:[],
            versionColumnSelect:[],
            dbOperator:[],
            dbDefaultType:[],
            loading:false,
            matchSeconds:0,
            id:null,
            previewDialogVisible:false,
            dialogTableTitle:[],
            dialogTableList:[],
            checkedIn:false,
            versionColumnSelectTable:[],
            lastTimeCursor:'',
            previewLoading:false

        }
    },
    created(){
        dbConfig().then(res=>{
          if(res.code == 200){
            this.dbOperator = res.data.dbOperator
            this.dbDefaultType = res.data.dbDefaultType
          }
        })
    },
    watch:{
        'stationId':{
            handler(newVal,oldVal){
                this.wareList = []
                this.wareSelectList = []
                this.dictSelect = []
                this.versionColumnSelect = []
                this.conditionList = []
                this.checkList = []
                this.tableList = []
            }
        },
        'codeId':{
            handler(newVal,oldVal){
                if(this.codeId && this.tabName == '2'){
                    this.clearData()
                    this.handleGetInWare()
                    this.getWareSelect()
                    setTimeout(()=>{
                        this.handleGetData(false)
                    },500)
                }else{
                    this.clearData()
                    this.loading = false
                }
            }
        },
        'copyCodeID':{
            handler(newVal,oldVal){
                if(this.copyCodeID != 0 && this.copyCodeID != null && this.tabName == '2'){
                    this.clearData()
                    this.handleGetInWare()
                    this.getWareSelect()
                    setTimeout(()=>{
                        this.handleGetData(true)
                    },500)
                }else if(this.copyCodeID == null && this.tabName == '2'){
                    this.clearData()
                    this.handleGetInWare()
                    this.getWareSelect()
                    this.loading = false
                }
            }
        },
        'tabName':{
            handler(newVal,oldVal){
                if(this.codeId && this.tabName == '2'){
                    this.clearData()
                    this.handleGetInWare()
                    this.getWareSelect()
                    setTimeout(()=>{
                        this.handleGetData(false)
                    },500)
                }else{
                    this.clearData()
                    this.loading = false
                }
            }
        }
    },
    methods: {
      clearData(){
        this.loading = true
        this.wareList = []
        this.wareSelectList = []
        this.dictSelect = []
        this.versionColumnSelect = []
        this.conditionList = []
        this.checkList = []
        this.tableList = []
      },
      getWareSelect(){
          DBlist({
              basinId:'',
              stationId:this.stationId,
              page:1,
              size:500
          }).then(res=>{
          if(res.code == 200){
              this.wareSelectList = res.data.list
          }else{
              this.wareSelectList = []
          }
          })
      },
      handleGetData(isCopy) {
        const code = isCopy ? this.copyCodeID : this.codeId;
        this.loading = true;
        pointDetail({
            codeId: code
        }).then(res => {
            if (res.code !== 200) {
                this.loading = false;
                this.$message.error('获取数据失败');
                return;
            }

            this.id = isCopy ? null : res.data.id;
            
            // 处理已有数据的情况
            if (res.data.dbSourceTables?.length > 0 && res.data.relationType === 'one-to-many') {
                this.handleExistingData(res.data);
            } else {
                // 处理新数据或空数据的情况
                this.handleNewData(isCopy);
            }
        }).catch(error => {
            console.error('获取数据出错:', error);
            this.loading = false;
            this.$message.error('获取数据时发生错误');
        });
    },

    // 处理已有数据
    handleExistingData(data) {
        this.conditionList = data.dbSourceTables || this.getDefaultConditionList();
        this.tableList = data.columnMaps || [];
        
        // 更新选中列表
        this.checkList = data.columnMaps?.map(item => item.targetColumn) || [];
        
        // 检查是否全选
        this.checkedIn = this.tableList.length === this.wareList.length;
        this.loading = false;
    },

    // 处理新数据
    async handleNewData(isCopy) {
        this.conditionList = this.getDefaultConditionList();
        
        if (!isCopy) {
            await this.setDefaultTableData();
        }
        
        this.loading = false;
    },

    // 获取默认的条件列表
    getDefaultConditionList() {
        const defaultCondition = {
            conditions: [],
            dbId: '',
            dbName: '',
            dbSchemaId: '',
            dbSchemaName: '',
            dictTableId: '',
            dictTableName: '',
            dictTimeColumnId: '',
            dictTimeColumnName: '',
            isMaster: false,
            matchSeconds: 0
        };
        
        return [{ ...defaultCondition }, { ...defaultCondition }];
    },

    // 设置默认表格数据
    async setDefaultTableData() {
        try {
            const response = await PowerPointQueryById({ id: this.codeId });
            
            if (response.code === 200) {
                const pointData = response.data.data;
                this.checkList = ['INSTR_ID', 'CODE_ID', 'TULI', 'REMARK'];
                
                this.tableList = [
                    this.createTableItem('INSTR_ID', 'DEFAULT', pointData.instR_ID),
                    this.createTableItem('CODE_ID', 'DEFAULT', pointData.id),
                    this.createTableItem('TULI', 'DEFAULT', pointData.pointName),
                    this.createTableItem('REMARK', 'DEFAULT', '工具抓取')
                ];
            } else {
                this.$message.warning('获取测点信息失败，使用空数据');
                this.tableList = [];
            }
        } catch (error) {
            console.error('获取测点信息出错:', error);
            this.$message.error('获取测点信息时发生错误');
            this.tableList = [];
        }
    },

    // 创建表格项辅助函数
    createTableItem(targetColumn, defaultType, defaultVal) {
        return {
            defaultType,
            defaultVal,
            sourceDbId: 0,
            sourceDbSchemaId: 0,
            sourceDictColumnId: 0,
            sourceDictTableId: 0,
            targetColumn
        };
    },
    handleGetCheckedWare() {
      if (this.checkList.length === 0) {
          this.tableList = [];
          this.checkedIn = false;
          return;
      }

      const list = this.checkList.map(item => {
          const existingItem = this.tableList.find(f => f.targetColumn === item);
          
          return existingItem || {
              targetColumn: item,
              sourceDbId: this.formInline.sourceDbId || '',
              sourceDbSchemaId: this.formInline.sourceDbSchemaId || '',
              sourceDictTableId: this.formInline.dictTableId || '',
              sourceDictColumnId: '',
              defaultType: '',
              defaultVal: ''
          };
      });
      this.tableList = [...list];
      this.checkedIn = this.checkList.length === this.wareList.length;
    },
    // 部分联动
      // type1是匹配条件的联动
      // type2是表格部分的联动
      handleChangeDbID(val,index,type){
          // 数据库下拉框
          if(type == 1){
              const list = [...this.conditionList]
              const data = {...list[index]}
              data.dbId = val.id
              data.dbName = val.alias
              // 清空后面联动
              data.dbSchemaId = ''
              data.dbSchemaName = ''
              data.dictTableId = ''
              data.dictTableName = ''
              data.dictTimeColumnId = ''
              data.dictTimeColumnName = ''
              //清空下面条件    
              data.conditions = []
              this.dbSchemas = [] //模式
              this.dictSelect = [] //数据表
              this.versionColumnSelect = [] //时间列
              // 回填数据
              list[index] = {...data}
              this.conditionList = [...list]
          }else if(type == 2){
              const list = [...this.tableList]
              const data = {...list[index]}
              data.sourceDbId = val.id
              data.sourceDbName = val.alias
              // 清空后面联动
              data.sourceDbSchemaId = ''
              data.sourceDbSchemaName = ''
              data.sourceDictColumnId = ''
              data.sourceDictColumnName = ''
              data.sourceDictTableId = ''
              data.sourceDictTableName = ''
              this.dbSchemas = [] //模式
              this.dictSelect = [] //数据表
              this.versionColumnSelect = [] //时间列
              // 回填数据
              list[index] = {...data}
              this.tableList = [...list]
          }
          this.wareSelectList.forEach(item=>{
              if(item.id == val.id){
                  this.dbSchemas = item.dbSchemas
              }
          })
      },
      handleGetInWare(){
        tableColumnList({
            codeId:this.codeId
        }).then(res=>{
          if(res.code == 200){
              this.wareList = res.data
          }else{
              this.wareList = []
          }
        })
      },
      handleChangeCheckAll(val){
        if (val) {
            // 全选情况
            this.checkList = this.wareList.map(item => item.columnName);
        } else {
          // 部分选择情况
          this.checkList = ['INSTR_ID', 'CODE_ID', 'TULI', 'REMARK'];
          // 获取数据并设置默认值
          PowerPointQueryById({ id: this.codeId }).then(res => {
            if (res.code === 200) {
                const { data } = res.data;
                this.tableList = [
                    {
                        defaultType: 'DEFAULT',
                        defaultVal: data.instR_ID,
                        sourceDbId: '',
                        sourceDbSchemaId: '',
                        sourceDictColumnId: '',
                        sourceDictTableId: '0',
                        targetColumn: 'INSTR_ID',
                        uniqueIndex: ''
                    },
                    {
                        defaultType: 'DEFAULT',
                        defaultVal: data.id,
                        sourceDbId: '',
                        sourceDbSchemaId: '',
                        sourceDictColumnId: '',
                        sourceDictTableId: '0',
                        targetColumn: 'CODE_ID',
                        uniqueIndex: ''
                    },
                    {
                        defaultType: 'DEFAULT',
                        defaultVal: data.pointName,
                        sourceDbId: '',
                        sourceDbSchemaId: '',
                        sourceDictColumnId: '',
                        sourceDictTableId: '0',
                        targetColumn: 'TULI',
                        uniqueIndex: ''
                    },
                    {
                        defaultType: 'DEFAULT',
                        defaultVal: '工具抓取',
                        sourceDbId: '',
                        sourceDbSchemaId: '',
                        sourceDictColumnId: '',
                        sourceDictTableId: '0',
                        targetColumn: 'REMARK',
                        uniqueIndex: ''
                    }
                ];
            }
          }).catch(error => {
            console.error('获取数据失败:', error);
          });
        }
        // 更新选中项
        this.handleGetCheckedWare();
      },
      handleGetCheckedWare(){
        const list = []
        if(this.checkList.length > 0){
            this.checkList.forEach(item=>{
                if(this.tableList.length > 0){
                    const name = this.tableList.filter(f=>{return f.targetColumn == item})
                    if(name.length > 0){
                        list.push(name[0])
                    }else{
                        list.push({
                            targetColumn:item,
                            sourceDbId:'',
                            sourceDbName:'',
                            sourceDbSchemaId:'',
                            sourceDbSchemaName:'',
                            sourceDictColumnId:'',
                            sourceDictColumnName:'',
                            sourceDictTableId:'',
                            sourceDictTableName:'',
                            defaultType:null,
                            defaultVal:null,
                        })
                    }
                }else{
                    list.push({
                        targetColumn:item,
                        sourceDbId:'',
                        sourceDbName:'',
                        sourceDbSchemaId:'',
                        sourceDbSchemaName:'',
                        sourceDictColumnId:'',
                        sourceDictColumnName:'',
                        sourceDictTableId:'',
                        sourceDictTableName:'',
                        defaultType:null,
                        defaultVal:null,
                    })
                }
            })
            this.tableList = [...list]
        }else{
            this.tableList = []
        }
        
        if(this.checkList.length == this.wareList.length){
            this.checkedIn = true
        }else{
            this.checkedIn = false
        }
      },
      hadnleAddCondtionMore(){
        this.conditionList.push({
            conditions:[],
            dbId:'',
            dbName:'',
            dbSchemaId:'',
            dbSchemaName:'',
            dictTableId:'',
            dictTableName:'',
            dictTimeColumnId:'',
            dictTimeColumnName:'',
            isMaster:false,
            matchSeconds:0
        })
      },
      handleChangeDbSchemaId(val,index,type){
            if(type == 1){
                const list = [...this.conditionList]
                const data = {...list[index]}
                data.dbSchemaId = val.schemaId
                data.dbSchemaName = val.schemaName
                this.dbSchemas.forEach(item=>{
                    if(item.schemaId == val.schemaId){
                        data.dictVersionId = val.dictVersionId
                    }
                })
                // 清空后面联动
                data.dictTableId = ''
                data.dictTableName = ''
                data.dictTimeColumnId = ''
                data.dictTimeColumnName = ''
                //清空下面条件    
                data.conditions = []
                this.dictSelect = [] //数据表
                this.versionColumnSelect = [] //时间列
                // 回填数据 
                list[index] = {...data}
                this.conditionList = [...list]
            }else if(type == 2){
                const list = [...this.tableList]
                const data = {...list[index]}
                data.sourceDbSchemaId = val.schemaId
                data.sourceDbSchemaName = val.schemaName
                this.dbSchemas.forEach(item=>{
                    if(item.schemaId == val.schemaId){
                        data.dictVersionId = val.dictVersionId
                    }
                })
                // 清空后面联动
                data.sourceDictColumnId = ''
                data.sourceDictColumnName = ''
                data.sourceDictTableId = ''
                data.sourceDictTableName = ''
                this.dictSelect = [] //数据表
                this.versionColumnSelect = [] //时间列
                // 回填数据
                list[index] = {...data}
                this.tableList = [...list]
            }
            
        },
        handleFocusDbSchemaId(dbId,type){
           if(dbId){
            
            this.wareSelectList.forEach(item=>{
                if(item.id == dbId){

                    this.dbSchemas = item.dbSchemas
                }
            })
           }else{
            this.dbSchemas = []
           }
        },
        handleFocusDictTableID(dictVersionId){
            if(dictVersionId){
                versionTable({
                    dictVersionId:dictVersionId
                    }).then(res=>{
                    if(res.code == 200){
                        this.dictSelect = res.data
                    }else{
                        this.dictSelect = []
                    }
                })
            }else{
                this.dictSelect = []
            }
        },
        handleFocusdictTimeColumnId(dictTableId){
            if(dictTableId){
                versionColumn({
                    dictTableId:dictTableId
                }).then(res=>{
                    if(res.code == 200){
                        this.versionColumnSelect = res.data
                    }else{
                        this.versionColumnSelect = []
                    }
                })
            }else{
                this.versionColumnSelect = [] 
            }
        },                                       
        handleChangeDictTableID(val,index,type){
            if(type == 1){
                const list = [...this.conditionList]
                const data = {...list[index]}
                data.dictTableId = val.id
                data.dictTableName = val.tableName
                // 清空后面联动
                data.dictTimeColumnId = ''
                data.dictTimeColumnName = ''
                //清空下面条件    
                data.conditions = []
                this.versionColumnSelect = [] //时间列
                // 回填数据 
                list[index] = {...data}
                this.conditionList = [...list]
            }else if(type == 2){
                const list = [...this.tableList]
                const data = {...list[index]}
                data.sourceDictTableId = val.id
                data.sourceDictTableName = val.tableName
                // 清空后面联动
                data.sourceDictColumnId = ''
                data.sourceDictColumnName = ''
                this.versionColumnSelect = [] //时间列
                // 回填数据
                list[index] = {...data}
                this.tableList = [...list]
            }
        },
        handleDelConditionItem(index,subIndex){
            this.conditionList[index].conditions.splice(subIndex,1)
        },
        handlePreview(){
          pointPreview({
                codeId:this.codeId
            }).then(res=>{
                if(res.code == 200){
                    this.previewDialogVisible = true
                    this.dialogTableTitle = res.data.tableTitleList || []
                    this.dialogTableList = res.data.dataList || []
                }else{
                  this.$message.error(res.msg)
                }
            })
        },
        hadnleSaveCondtion(){
          const conditionList = []
            const tableList = []
            this.conditionList.forEach((item,index)=>{
                const d = {
                    dbId:item.dbId,
                    dbSchemaId:item.dbSchemaId,
                    dictTableId:item.dictTableId,
                    dictTimeColumnId:item.dictTimeColumnId,
                    matchSeconds:!item.isMaster ? Number(item.matchSeconds) : 0,
                    isMaster:item.isMaster,
                    conditions:[],
                    uniqueIndex:(index + 1).toString()
                }
                item.conditions.forEach(sub=>{
                    const a = {
                        dictColumnId:sub.dictColumnId,
                        operator:sub.operator,
                        conditionVal:sub.conditionVal
                    }
                    d.conditions.push(a)
                })   
                conditionList.push(d)
            })

            this.tableList.forEach(item=>{
                const d = {
                    targetColumn:item.targetColumn,
                    // sourceDbId:item.sourceDbId || 0,
                    // sourceDbSchemaId:item.sourceDbSchemaId || 0,
                    // sourceDictTableId:item.sourceDictTableId || 0,
                    sourceDictColumnId:item.sourceDictColumnId || 0,
                    defaultType:item.defaultType,
                    defaultVal:item.defaultVal,
                    uniqueIndex:item.uniqueIndex || ''
                }
                tableList.push(d)
            })
            const data = {
                id:this.id || null,
                stationId:this.stationId,
                codeId:this.codeId,
                relationType:'one-to-many',
                dbSourceTables:conditionList,
                columnMaps:tableList
            }
            pointSave(data).then(res=>{
                if(res.code == 200){
                    this.handleGetData(false)
                    this.$message.success('保存成功')
                }else{
                    this.$message.error(res.msg)
                }
            })
        },
        handleChangeIndex(){
          changeIndex({
              codeId:this.codeId,
              lastTimeCursor:this.lastTimeCursor
          }).then(res=>{
              if(res.code == 200){
                  this.$message.success('修改成功')
              }else{
                  this.$message.error(res.msg)
              }
          })
        },
        hadnleAddCondtionItem(index){
            this.conditionList[index].conditions.push({
                conditionVal:'',
                dictColumnId:'',
                dictColumnName:'',
                operator:''
            })
        },
    }
}
</script>

<style scoped lang="scss">
.data-mapping-container {
  padding: 10px;
  height: calc(100vh - 240px);
  .mapping-content {
    display: flex;
    gap: 10px;
    .field-selection-panel {
      min-width: 280px;
      height: calc(100vh - 260px);
      background: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      display: flex;
      flex-direction: column;
      
      .panel-header {
        padding: 16px;
        border-bottom: 1px solid #e6ebf5;
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        h3 {
          margin: 0;
          font-size: 14px;
          color: #303133;
        }
      }
      
      .panel-body {
        height:calc(100vh - 280px);
        overflow-y: auto;
        
        .search-input {
          padding: 12px;
        }
        
        .field-list {
          flex: 1;
          overflow-y: auto;
          padding: 0 12px 12px;
          
          .field-item {
            padding: 8px 0;
            border-bottom: 1px dashed #e6ebf5;
            
            &:last-child {
              border-bottom: none;
            }
            
            .field-name {
              font-size: 13px;
            }
            
            .field-info {
              margin-left: 4px;
              color: #909399;
            }
          }
        }
      }
      
      .empty-state {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        color: #909399;
        
        .empty-icon {
          font-size: 48px;
          margin-bottom: 12px;
        }
        
        p {
          margin: 0;
          font-size: 14px;
        }
      }
    }
    
    .configuration-panel {
      flex: 1;
      height: calc(100vh - 300px);
      overflow: auto;
      .config-card {
        border-radius: 4px;
        
        ::v-deep .el-card__header {
          padding: 12px 16px;
          background-color: #fafafa;
        }
        
        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .card-title {
            font-weight: bold;
            color: #303133;
            
            i {
              margin-right: 6px;
              color: #409EFF;
            }
          }
        }
        
        &.data-source-card {
          .data-source-form {
            padding: 0 8px;
          }
          
          .conditions-section {
            margin-top: 16px;
            border-top: 1px solid #e6ebf5;
            padding-top: 16px;
            
            .section-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
              margin-bottom: 12px;
              font-weight: bold;
              color: #606266;
            }
            
            .conditions-list {
              .condition-item {
                display: flex;
                align-items: center;
                margin-bottom: 12px;
                padding: 8px;
                background-color: #f9fafc;
                border-radius: 4px;
              }
              
              .no-conditions {
                text-align: center;
                padding: 20px;
                color: #909399;
                background-color: #f9fafc;
                border-radius: 4px;
                
                i {
                  margin-right: 6px;
                }
              }
            }
          }
        }
        
        &.field-mapping-card {
          .cursor-config {
            display: flex;
            align-items: center;
            font-size: 13px;
            color: #606266;
          }
          
          .mapping-table {
            ::v-deep .el-table__header-wrapper th {
              background-color: #f5f7fa;
            }
          }
        }
      }
      
      .action-bar {
        background: #fff;
        padding: 16px;
        border-radius: 4px;
        text-align: center;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      }
    }
  }
}

.preview-dialog {
  .preview-content {
    .preview-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 16px;
      
      .preview-count {
        color: #606266;
        font-size: 14px;
      }
    }
  }
}

.panel-header1 {
    padding: 16px 24px;
    border-bottom: 1px solid #e2e8f0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background:#fff;
    margin: -11px 0 10px -10px;
    
    .panel-title {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #1e293b;
      display: flex;
      align-items: center;
      gap: 12px;
      
      .code-id {
        font-size: 12px;
        color: #64748b;
        font-weight: normal;
        background: #f1f5f9;
        padding: 2px 8px;
        border-radius: 4px;
      }
    }
    
    .panel-actions {
      display: flex;
      gap: 8px;
    }
  }

.panel-content {
    flex: 1;
    overflow: auto;
    background: #fafafa;
  }


  .source-item {
    margin-bottom: 10px;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
  
  .source-card {
    background: #f8fafc;
    border: 1px solid #e8e8e8;
    border-radius: 4px;
    padding: 20px;
    transition: all 0.3s ease;
    
    &:hover {
      box-shadow: 0 4px 16px rgba(0, 0, 0, 0.06);
    }
  }
  
  .source-config {
    margin-bottom: 20px;
    
    .config-row {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;
      align-items: flex-end;
    }
    
    .config-group {
      display: flex;
      flex-direction: column;
      gap: 6px;
      
      .config-label {
        font-size: 12px;
        color: #606266;
        font-weight: 500;
      }
      
      .config-select {
        width: 160px;
        
        ::v-deep .el-input__inner {
          border-radius: 6px;
        }
      }
      
      &.master-group {
        flex-direction: row;
        align-items: center;
        gap: 8px;
      }
    }
    
    .delete-btn {
      margin-left: auto;
      border-radius: 6px;
    }
  }
  
  .condition-config {

    .condition-actions {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      font-weight: bold;
      color: #606266;
    }
    
    .condition-row {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 12px;
      padding: 12px;
      background: #ffffff;
      border-radius: 8px;
      border: 1px solid #e8e8e8;
      
      .condition-fields {
        display: flex;
        gap: 6px;
        flex: 1;
        
        .condition-select,
        .operator-select {
          flex: 1;
          
          ::v-deep .el-input__inner {
            border-radius: 6px;
          }
        }
        
        .value-input {
          flex: 2;
          
          ::v-deep .el-input__inner {
            border-radius: 6px;
          }
        }
      }
    }
  }
</style>